var express = require('express');
var router = express.Router();
var uuid = require('node-uuid');
var md5 = require('md5');
var jwt = require('jsonwebtoken');
var sql = require('../sql');
var utils = require('../utils');
var User = require('../sql/col/User');

router.get('/', function(req, res, next) {
    res.send('user相关接口')
});

/**
 * @api {post} /api/user/sendCode 发送短信验证码
 * @apiName PostUserSendCode
 * @apiGroup user
 * 
 * @apiParam { String } tel 手机号
 * 
 * @apiSuccessExample {json} Success-Response:
 *  res.send({
        code: '200',
        message: '短信已发送',
        telCode: code
    })
    res.send({
        code: '10002',
        message: '短信发送失败',
    })
     res.send({
        code: '10001',
        message:'手机号已注册'
    })
 * @apiSampleRequest /api/user/sendCode
 * @apiVersion 0.0.0
 */
router.post('/sendCode', (req, res, next) => {
    const { tel } = req.body
    const code = Math.floor(Math.random()* 900000 + 100000) // 随机6位数
    sql.find(User, { tel }, {_id:0}).then(data => {
        if(data.length === 0) {
            utils.sendCode(tel, code).then(() => {
                res.send({
                    code: '200',
                    message: '短信已发送',
                    telCode: code // 真实上线不要发送
                })
            }).catch(() => {
                res.send({
                    code: '10002',
                    message: '短信发送失败',
                })
            })
        } else {
            res.send({
                code: '10001',
                message:'手机号已注册'
            })
        }
    })
})

/**
 * @api {post} /api/user/register 用户注册
 * @apiName PostUserRegister
 * @apiGroup user
 * 
 * @apiParam { String } username 用户名
 * @apiParam { String } tel 手机号
 * @apiParam { String } password 密码
 * 
 * 
 * @apiSuccessExample {json} Success-Response:
 *  res.send({
        code: '200',
        message: '注册成功'
    })
    res.send({
        code: '10001',
        message: '该手机号已被注册'
    })
    res.send({
        code: '10003',
        message: '该用户名已被注册'
    })
 * @apiSampleRequest /api/user/register
 * @apiVersion 0.0.0
 */
router.post('/register', (req, res, next) => {
    const { username, tel, password } = req.body
    sql.find(User, { username }, {_id:0}).then(data1 => {
        if (data1.length === 0) {
            sql.find(User, { tel }, {_id:0}).then(data2 => {
                if (data2.length === 0) {
                    const insertData = {
                        userid: 'user_' + uuid.v1(),
                        username,
                        nickname: '海购' + new Date().getTime() + Math.floor(Math.random()*10000),
                        password: md5(password),
                        tel,
                        email: '',
                        avatar: 'https://dss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=1373560079,871367259&fm=26&gp=0.jpg',
                        sex: -1
                    }
                    sql.insert(User,insertData).then(()=> {
                        res.send({
                            code: '200',
                            message: '注册成功'
                        })
                    })
                } else {
                    res.send({
                        code: '10001',
                        message: '该手机号已被注册'
                    })
                }
            })
        } else {
            res.send({
                code: '10003',
                message: '该用户名已被注册'
            })
        }
    })
})

/**
 * @api {post} /api/user/login 用户登录
 * @apiName PostUserLogin
 * @apiGroup user
 * 
 * @apiParam { String } loginname 用户名或者手机号
 * @apiParam { String } password 密码
 * 
 * 
 * @apiSuccessExample {json} Success-Response:
 *  res.send({
        code: '10004',
        message: '用户名和手机号均不存在'
    })
    res.send({
        code: '10005',
        message: '密码错误'
    })
    res.send({
        code: '200',
        message: '登录成功',
        data: data2[0].userid,
        token: 'xxxxxxxx'
    })
 * @apiSampleRequest /api/user/login
 * @apiVersion 0.0.0
 */
router.post('/login', (req, res, next) => {
    const { loginname, password } = req.body
    sql.find(User, { $or: [{username: loginname}, {tel:loginname}] }, {_id:0}).then(data1 => {
        if (data1.length === 0) {
            res.send({
                code: '10004',
                message: '用户名和手机号均不存在'
            })
        } else {
            sql.find(User, { password: md5(password),$or:[ { username: loginname }, { tel: loginname }]}).then(data2 => {
                if (data2.length === 0) {
                    res.send({
                        code: '10005',
                        message: '密码错误'
                    })
                } else{
                    const token = jwt.sign( {userid: data2[0].userid, password:md5(password)}, 'lmx', {
                        expiresIn: 7 * 24 * 60 * 60 // 7 days
                        // expiresIn: 20
                    })
                    res.send({
                        code: '200',
                        message: '登录成功',
                        data: {
                            userid: data2[0].userid, // 用户的id，前端保存起来，以后加入购物车以及访问数据时使用
                            token
                        }
                    })
                }
            })
        }
    })
})


/**
 * @api {post} /api/user/getInfo 获取用户信息
 * @apiName PostUserGetInfo
 * @apiGroup user
 * 
 * @apiParam { String } userid 用户id
 * @apiParam { String } token 头信息/get/post提交
 * 
 * @apiSuccessExample {json} Success-Response:
 *  res.send({
      code: '200',
      message: '获取用户信息',
      data
    })
 * @apiSampleRequest /api/user/getInfo
 * @apiVersion 0.0.0
 */
router.post('/getInfo', (req, res, next) => {
    utils.validateToken(req, res).then(() => {
        const { userid } = req.body
        sql.find(User, { userid }, {_id:0,password:0}).then(data => {
            res.send({
                code: '200',
                message: '获取用户信息',
                data
            })
        })
    })
})

module.exports = router;